<?php

/**
* @Copyright 2011 DSGame
* 
*/

class BaseDSgame {

  /**
  * Version.
  */
  const DSGAME_API_VERSION = '1.0';

  /**
  * The Application API Key.
  *
  * @var string
  */
  protected $apikey;

  /**
  * The Application API Secret.
  *
  * @var string
  */
  protected $secretkey;

  /**
  * The Application API Name.
  *
  * @var string
  */
  protected $apiname;

  /**
  * The Application API UserName.
  *
  * @var string
  */
  protected $username;

  /**
  * The OAuth access token received in exchange for a valid authorization
  * code.  null means the access token has yet to be determined.
  *
  * @var string
  */
  protected $accessToken = null;

  /**
  * The Application Partner Array Config.
  *
  * @var array
  */
  protected $partner_array = array (array ('id' => '1', 'secretkey' => 'thuands', 'name' => 'Thuan Flash' ) );

  /**
  * Set Application Partner Array Config
  * @param string $keyvar
  */
  public function setPartnerArray($keyvar) {
    $this->key = $keyvar;
  }

  public function __construct($config = array()) {

    if (! isset ( $config ["apikey"] ) || ! isset ( $config ["secretkey"] )) {
      $this->setError ( - 9999, "CONFIG ERROR", "something miss in config", true );
    } else {

      // check partner
      if (! $this->checkPartner ( $config ["apikey"], $config ['secretkey'] )) {
        $this->setError ( - 9990, "CONFIG ERROR", "partner invalid", true );
      }

      $this->apikey = $config ["apikey"];
      $this->secretkey = $config ["secretkey"];

      if (isset ( $config ["username"] )) {
        $this->username = $config ["username"];
      }

      if (isset ( $config ["accessToken"] )) {
        $this->accessToken = $config ["accessToken"];
        if (! $this->checkAccessToken ()) {
          $this->setError ( - 9991, "INVALID", "Access Token is missing, invalid or expried", true );
        }
      }

    }

  }

  /**
  * Sets the access token for api calls.  Use this if you get
  * your access token by other means and just want the SDK
  * to use it.
  * 
  * @param $accessToken
  */
  public function setAccessToken($accessToken) {
    $this->accessToken = $accessToken;
  }

  /**
  * Return access token was sets   
  *
  * @param string $access_token an access token.
  * 
  */
  public function getAccessToken() { 
    return $this->accessToken;   
  }

  

  /**
  * Check Access Token ban doi tac lay co dung ko
  * 
  * @return boolean
  */
  public function checkAccessToken() {

    global $memcache;

    $data = array ();

    // if file exists
    if ($memcache->get ( md5 ( 'token' . $this->username ) )) {
      // if ($_SESSION [md5 ( $this->apikey )] == $this->accessToken) {
      if ($memcache->get ( md5 ( 'token' . $this->username ) ) == $this->accessToken) {
        $this->createAccessToken();
        return true;
      }
    }
    return false;

  }

  /**
  * Return json data
  * 
  * @author tientm
  * @param string $string
  * @return json
  */
  public function setStringResult($token = null, $value = null) {
    return json_encode ( array (REST_CODE_LANG => 1, REST_TYPE_LANG => 'SUCCESS', REST_VALUE_LANG => $value, 'token' => $token ) ) . "\n";
  }

  /**
  * Return json data
  * 
  * @author tientm
  * @param object $obj
  * @return json
  */
  public function setObjectResult($token = array(), $obj = null) {
    return json_encode ( array (REST_CODE_LANG => 1, REST_TYPE_LANG => 'SUCCESS', REST_VALUE_LANG => serialize ( $obj ), 'token' => $token ) ) . "\n";
  }

  /**
  * Prints to the error log if you aren't in command line mode.
  *
  * @param string $msg Log message
  */
  protected static function errorLog($msg) {
    // disable error log if we are running in a CLI environment
    // @codeCoverageIgnoreStart
    if (php_sapi_name () != 'cli') {
      error_log ( $msg );
    }

    // uncomment this if you want to see the errors on the page
    // print 'error_log: '.$msg."\n";
    // @codeCoverageIgnoreEnd
  }

  /**
  * Base64 encoding that doesn't need to be urlencode()ed.
  * Exactly the same as base64_encode except it uses
  * - instead of +
  * _ instead of /
  *
  * @param string $input base64UrlEncoded string
  * @return string
  */
  protected static function base64UrlDecode($input) {
    return base64_decode ( strtr ( $input, '-_', '+/' ) );
  }

  /**
  * Show return of value with option die.
  * 
  * @author tientm
  * 
  * @param int $code
  * @param string $type
  * @param string $msg
  */
  public function setValue($msg = '', $die = false, $json = true) {
    $exception = new DSException ( 1, 'SUCCESS', $msg );
    if ($die) {
      if ($json) {
        die ( $exception->__toJson () );
      } else {
        die ( $exception->__toString () );
      }
    } else {
      if ($json) {
        echo $exception->__toJson ();
      } else {
        echo $exception->__toString ();
      }
    }
  }

  /**
  * Show error or value return with option die.
  * 
  * @author tientm
  * 
  * @param int $code
  * @param string $type
  * @param string $msg
  */
  public function setError($code = 0, $type = '', $msg = '', $die = false, $json = true) {
    $exception = new DSException ( $code, $type, $msg );
    if ($die) {
      if ($json) {
        die ( $exception->__toJson () );
      } else {
        die ( $exception->__toString () );
      }
    } else {
      if ($json) {
        echo $exception->__toJson ();
      } else {
        echo $exception->__toString ();
      }
    }
  }

  /**
  * Check api key request from client.
  * 
  * @author tientm
  * 
  * @param string $paramCheck
  * @param string $apiKey
  * @return array $status trang thai tra ve
  */
  public function checkPartner($parnerid = null, $secretkey = null) {
    if ($parnerid && $secretkey) {
      foreach ( $this->partner_array as $pa ) {
        if ($pa ['id'] == $parnerid && $pa ['secretkey'] == $secretkey) {
          $this->apiname = $pa ['name'];
          return true;
        }
      }
    }
    return false;
  }

  function login($md5password, $sessionkey) {

    global $db, $memcache;

    $data = array ();        

    // if user info loaded 
    if ($memcache->get ( $sessionkey )) {
      return $memcache->get ( $sessionkey );
    } else {
      // process login
      if ($this->username == 'tiends' && $md5password == md5 ( '1234567' )) {

        $data ['userid'] = '1';
        $data ['username'] = 'tiends';
        $data ['useremail'] = 'tienrocker@gmail.com';
        $data ['timestamp'] = time();
        $data ['sessionkey'] = $sessionkey;

        $memcache->set ( $sessionkey, json_encode ( $data ), 300 );
        return $memcache->get ( $sessionkey );
      }
    }
    return false;
  }

}
 